<template>
  <div class="process-flow-container">
    <div ref="threeContainer" class="three-container"></div>
    <div class="control-panel">
      <div class="flow-status">
        <div class="status-item" v-for="(item, index) in processSteps" :key="index">
          <div class="status-icon" :class="{ active: item.active }"></div>
          <div class="status-info">
            <span class="status-name">{{ item.name }}</span>
            <div class="status-details">
              <div class="status-value">{{ item.value }}</div>
              <div class="status-pressure">压力: {{ parseFloat(item.pressure).toFixed(2) }} MPa</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

export default {
  name: 'ProcessFlow3D',
  data() {
    return {
      processSteps: [
        { name: '原料仓', active: true, value: '85%', pressure: '2.35', position: [-15, 3.5, 8] }, // 调整位置，增加高度0.5，向前移动3个单位
        { name: '输送带', active: true, value: '运行中', pressure: '1.82', position: [0, 1.5, 8] }, // 调整位置，向前移动3个单位
        { name: '混合机', active: true, value: '1200rpm', pressure: '3.67', position: [0, 2.5, -2] }, // 调整位置，向前移动3个单位，增加高度0.5
        { name: '回转窑', active: true, value: '1450°C', pressure: '4.23', position: [-12, 3.5, -12] }, // 调整位置，向前移动3个单位，增加高度0.5
        { name: 'n', active: false, value: '待入库', pressure: '1.95', position: [8, 3, -12] } // 调整位置，向前移动3个单位，增加高度0.5
      ]
    }
  },
  setup() {
    // 将Three.js对象放在setup中，避免Vue响应式代理
    const threeObjects = {
      scene: null,
      camera: null,
      renderer: null,
      animationId: null,
      controls: null,
      raycaster: null,
      mouse: null,
      flowParticles: null,
      equipmentMeshes: {},
      selectedEquipment: null,
      labels: [],
      flowPaths: []
    }

    return {
      threeObjects
    }
  },
  mounted() {
    this.$nextTick(() => {
      try {
        this.initThreeJS()
        this.createScene()
        this.animate()
        this.startDataUpdate()
      } catch (error) {
        console.error('Three.js initialization error:', error)
      }
    })
  },
  beforeUnmount() {
    // 清理动画循环
    if (this.threeObjects.animationId) {
      cancelAnimationFrame(this.threeObjects.animationId)
      this.threeObjects.animationId = null
    }

    // 清理事件监听器
    if (this.threeObjects.renderer && this.threeObjects.renderer.domElement) {
      this.threeObjects.renderer.domElement.removeEventListener('click', this.onMouseClick)
      this.threeObjects.renderer.domElement.removeEventListener('mousemove', this.onMouseMove)
    }

    // 清理窗口事件监听器
    window.removeEventListener('resize', this.onWindowResize)

    // 清理Three.js对象
    if (this.threeObjects.controls) {
      this.threeObjects.controls.dispose()
      this.threeObjects.controls = null
    }

    if (this.threeObjects.renderer) {
      this.threeObjects.renderer.dispose()
      this.threeObjects.renderer = null
    }

    // 清理场景中的对象
    if (this.threeObjects.scene) {
      this.threeObjects.scene.clear()
      this.threeObjects.scene = null
    }

    this.threeObjects.camera = null
    this.threeObjects.raycaster = null
    this.threeObjects.mouse = null
    this.threeObjects.flowParticles = null
    this.threeObjects.equipmentMeshes = {}
  },
  methods: {
    initThreeJS() {
      // 检查容器是否存在
      if (!this.$refs.threeContainer) {
        console.error('Three.js container not found')
        return
      }

      const containerWidth = this.$refs.threeContainer.clientWidth || 800
      const containerHeight = this.$refs.threeContainer.clientHeight || 600

      // 使用threeObjects来存储Three.js对象，避免Vue代理
      this.threeObjects.scene = new THREE.Scene()
      this.threeObjects.scene.background = new THREE.Color(0x0a0a0a)

      this.threeObjects.camera = new THREE.PerspectiveCamera(
        75,
        containerWidth / containerHeight,
        0.1,
        1000
      )
      this.threeObjects.camera.position.set(0, 15, 25)
      this.threeObjects.camera.lookAt(0, 0, 0)

      this.threeObjects.renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
        preserveDrawingBuffer: false
      })
      this.threeObjects.renderer.setSize(containerWidth, containerHeight)
      this.threeObjects.renderer.shadowMap.enabled = false
      this.threeObjects.renderer.outputColorSpace = THREE.SRGBColorSpace

      // 安全地添加到DOM
      try {
        this.$refs.threeContainer.appendChild(this.threeObjects.renderer.domElement)
      } catch (error) {
        console.error('Failed to append renderer to DOM:', error)
        return
      }

      // 添加轨道控制器
      this.threeObjects.controls = new OrbitControls(this.threeObjects.camera, this.threeObjects.renderer.domElement)
      this.threeObjects.controls.enableDamping = true
      this.threeObjects.controls.dampingFactor = 0.05
      this.threeObjects.controls.screenSpacePanning = false
      this.threeObjects.controls.minDistance = 10
      this.threeObjects.controls.maxDistance = 100
      this.threeObjects.controls.maxPolarAngle = Math.PI / 2

      // 添加鼠标交互
      this.threeObjects.raycaster = new THREE.Raycaster()
      this.threeObjects.mouse = new THREE.Vector2()

      // 使用箭头函数避免this绑定问题
      this.threeObjects.renderer.domElement.addEventListener('click', (event) => {
        this.onMouseClick(event)
      })
      this.threeObjects.renderer.domElement.addEventListener('mousemove', (event) => {
        this.onMouseMove(event)
      })

      // 添加灯光
      this.addLights()

      // 添加窗口大小调整监听
      window.addEventListener('resize', () => {
        this.onWindowResize()
      })
    },

    addLights() {
      // 环境光
      const ambientLight = new THREE.AmbientLight(0x404040, 0.4)
      this.threeObjects.scene.add(ambientLight)

      // 主光源 - 禁用阴影以避免错误
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
      directionalLight.position.set(10, 20, 10)
      directionalLight.castShadow = false
      this.threeObjects.scene.add(directionalLight)

      // 点光源（用于设备高亮）
      const pointLight = new THREE.PointLight(0x00ff88, 0.5, 50)
      pointLight.position.set(0, 10, 0)
      this.threeObjects.scene.add(pointLight)
    },

    createScene() {
      // 创建地面
      this.createGround()

      // 创建设备
      this.createRawMaterialSilo()
      this.createConveyorBelt()
      this.createMixer()
      this.createRotaryKiln()
      this.createProductWarehouse()

      // 创建连接管道
      this.createPipelines()

      // 创建流动粒子
      this.createFlowParticles()
    },

    createGround() {
      const groundGeometry = new THREE.PlaneGeometry(60, 40)
      const groundMaterial = new THREE.MeshLambertMaterial({
        color: 0x1a1a1a,
        transparent: true,
        opacity: 0.8
      })
      const ground = new THREE.Mesh(groundGeometry, groundMaterial)
      ground.rotation.x = -Math.PI / 2
      ground.receiveShadow = true
      this.threeObjects.scene.add(ground)

      // 添加网格线
      const gridHelper = new THREE.GridHelper(60, 30, 0x333333, 0x222222)
      this.threeObjects.scene.add(gridHelper)
    },

    createRawMaterialSilo() {
      // 原料仓 - 圆柱形储罐 (左上角)
      const siloGeometry = new THREE.CylinderGeometry(2, 2, 6, 16)
      const siloMaterial = new THREE.MeshPhongMaterial({
        color: 0x4a90e2,
        transparent: true,
        opacity: 0.9
      })
      const silo = new THREE.Mesh(siloGeometry, siloMaterial)
      silo.position.set(-15, 3.5, 8) // 更新位置匹配数据
      silo.castShadow = true
      this.threeObjects.scene.add(silo)
      this.threeObjects.equipmentMeshes.silo = silo

      // 添加标签
      this.addLabel('原料仓', -15, 7.5, 8) // 更新标签位置
    },

    createConveyorBelt() {
      // 输送带 - 长方形传送带 (右上角)
      const beltGeometry = new THREE.BoxGeometry(8, 0.5, 2)
      const beltMaterial = new THREE.MeshPhongMaterial({ color: 0x666666 })
      const belt = new THREE.Mesh(beltGeometry, beltMaterial)
      belt.position.set(0, 1.5, 8) // 更新位置匹配数据
      belt.castShadow = true
      this.threeObjects.scene.add(belt)
      this.threeObjects.equipmentMeshes.belt = belt

      // 传送带支架
      for (let i = 0; i < 4; i++) {
        const supportGeometry = new THREE.BoxGeometry(0.2, 2, 0.2)
        const supportMaterial = new THREE.MeshPhongMaterial({ color: 0x888888 })
        const support = new THREE.Mesh(supportGeometry, supportMaterial)
        support.position.set(-3 + i * 2, 0.5, 9) // 更新支架位置
        this.threeObjects.scene.add(support)
      }

      this.addLabel('输送带', 0, 3.5, 8) // 更新标签位置
    },

    createMixer() {
      // 混合机 - 复合几何体 (中间)
      const mixerGroup = new THREE.Group()

      // 主体
      const bodyGeometry = new THREE.CylinderGeometry(2.5, 2.5, 4, 8)
      const bodyMaterial = new THREE.MeshPhongMaterial({ color: 0xe74c3c })
      const body = new THREE.Mesh(bodyGeometry, bodyMaterial)
      body.castShadow = true
      mixerGroup.add(body)

      // 搅拌器
      const bladeGeometry = new THREE.BoxGeometry(4, 0.2, 0.5)
      const bladeMaterial = new THREE.MeshPhongMaterial({ color: 0x34495e })
      const blade = new THREE.Mesh(bladeGeometry, bladeMaterial)
      blade.position.y = 0.5
      mixerGroup.add(blade)

      mixerGroup.position.set(0, 2.5, -2) // 更新位置匹配数据
      this.threeObjects.scene.add(mixerGroup)
      this.threeObjects.equipmentMeshes.mixer = mixerGroup

      this.addLabel('混合机', 0, 5.5, -2) // 更新标签位置
    },

    createRotaryKiln() {
      // 回转窑 - 倾斜的圆柱体 (左下角)
      const kilnGeometry = new THREE.CylinderGeometry(1.5, 1.5, 12, 16)
      const kilnMaterial = new THREE.MeshPhongMaterial({
        color: 0xff6b35,
        emissive: 0x331100
      })
      const kiln = new THREE.Mesh(kilnGeometry, kilnMaterial)
      kiln.position.set(-12, 3.5, -12) // 更新位置匹配数据
      kiln.rotation.z = Math.PI / 12 // 轻微倾斜
      kiln.rotation.x = Math.PI / 2
      kiln.castShadow = true
      this.threeObjects.scene.add(kiln)
      this.threeObjects.equipmentMeshes.kiln = kiln

      this.addLabel('回转窑', -12, 6.5, -12) // 更新标签位置
    },

    createProductWarehouse() {
      // 成品库 - 方形仓库 (右下角)
      const warehouseGeometry = new THREE.BoxGeometry(6, 5, 6)
      const warehouseMaterial = new THREE.MeshPhongMaterial({
        color: 0x27ae60,
        transparent: true,
        opacity: 0.8
      })
      const warehouse = new THREE.Mesh(warehouseGeometry, warehouseMaterial)
      warehouse.position.set(8, 3, -12) // 更新位置匹配数据
      warehouse.castShadow = true
      this.threeObjects.scene.add(warehouse)
      this.threeObjects.equipmentMeshes.warehouse = warehouse

      this.addLabel('成品库', 8, 6.5, -12) // 更新标签位置
    },

    createPipelines() {
      // 创建连接管道 - 按照图片中的流向，更新为新的设备位置
      const pipelinePositions = [
        { from: [-13, 3, 8], to: [-2, 2, 8] },        // 原料仓到输送带 (水平)
        { from: [0, 2, 6], to: [0, 3, 0] },           // 输送带到混合机 (垂直向下)
        { from: [-2, 3, -2], to: [-10, 3.5, -10] },   // 混合机到回转窑 (斜向左下)
        { from: [-6, 3.5, -12], to: [6, 3, -12] }     // 回转窑到成品库 (水平)
      ]

      pipelinePositions.forEach((pipeline, index) => {
        this.createPipeline(pipeline.from, pipeline.to, index)
      })
    },

    createPipeline(from, to, index) {
      const direction = new THREE.Vector3().subVectors(
        new THREE.Vector3(...to),
        new THREE.Vector3(...from)
      )
      const length = direction.length()

      // 主管道
      const pipeGeometry = new THREE.CylinderGeometry(0.2, 0.2, length, 8)
      const pipeMaterial = new THREE.MeshPhongMaterial({
        color: 0x95a5a6,
        transparent: true,
        opacity: 0.7
      })
      const pipe = new THREE.Mesh(pipeGeometry, pipeMaterial)

      pipe.position.set(
        (from[0] + to[0]) / 2,
        (from[1] + to[1]) / 2,
        (from[2] + to[2]) / 2
      )

      pipe.lookAt(new THREE.Vector3(...to))
      pipe.rotateX(Math.PI / 2)

      this.threeObjects.scene.add(pipe)

      // 添加发光内管道效果
      const glowGeometry = new THREE.CylinderGeometry(0.15, 0.15, length, 8)
      const glowMaterial = new THREE.MeshBasicMaterial({
        color: index === 1 ? 0x00ffff : (index === 0 ? 0x4da6ff : (index === 2 ? 0x80ff80 : 0x00ff80)), // 青色系
        transparent: true,
        opacity: 0.6,
        emissive: index === 1 ? 0x004444 : (index === 0 ? 0x002244 : (index === 2 ? 0x004400 : 0x002200))
      })
      const glowPipe = new THREE.Mesh(glowGeometry, glowMaterial)

      glowPipe.position.copy(pipe.position)
      glowPipe.rotation.copy(pipe.rotation)

      this.threeObjects.scene.add(glowPipe)

      // 保存发光管道引用用于动画
      if (!this.threeObjects.glowPipes) {
        this.threeObjects.glowPipes = []
      }
      this.threeObjects.glowPipes.push(glowPipe)
    },

    createFlowParticles() {
      // 创建流动粒子系统 - 沿着管道路径流动
      const particleCount = 200 // 增加粒子数量
      const particles = new THREE.BufferGeometry()
      const positions = new Float32Array(particleCount * 3)
      const colors = new Float32Array(particleCount * 3)
      const velocities = new Float32Array(particleCount * 3)
      const sizes = new Float32Array(particleCount) // 添加大小属性
      const phases = new Float32Array(particleCount) // 添加相位属性用于脉冲动画

      // 定义流动路径点 - 与新的管道位置匹配，增强青色效果
      this.threeObjects.flowPaths = [
        // 原料仓到输送带 (水平流动，亮蓝色)
        { start: [-13, 3, 8], end: [-2, 2, 8], color: [0.3, 0.9, 1] },
        // 输送带到混合机 (垂直向下流动，明亮青色)
        { start: [0, 2, 6], end: [0, 3, 0], color: [0, 1, 1] },
        // 混合机到回转窑 (斜向左下流动，青橙色)
        { start: [-2, 3, -2], end: [-10, 3.5, -10], color: [0.5, 1, 0.8] },
        // 回转窑到成品库 (水平流动，青绿色)
        { start: [-6, 3.5, -12], end: [6, 3, -12], color: [0, 1, 0.8] }
      ]

      for (let i = 0; i < particleCount; i++) {
        const pathIndex = Math.floor(Math.random() * this.threeObjects.flowPaths.length)
        const path = this.threeObjects.flowPaths[pathIndex]
        const t = Math.random()

        // 沿路径插值位置
        positions[i * 3] = path.start[0] + t * (path.end[0] - path.start[0])
        positions[i * 3 + 1] = path.start[1] + t * (path.end[1] - path.start[1])
        positions[i * 3 + 2] = path.start[2] + t * (path.end[2] - path.start[2])

        // 设置更亮的颜色
        colors[i * 3] = path.color[0]
        colors[i * 3 + 1] = path.color[1]
        colors[i * 3 + 2] = path.color[2]

        // 设置速度
        velocities[i * 3] = (path.end[0] - path.start[0]) * 0.02 // 增加速度
        velocities[i * 3 + 1] = (path.end[1] - path.start[1]) * 0.02
        velocities[i * 3 + 2] = (path.end[2] - path.start[2]) * 0.02

        // 设置随机大小和相位
        sizes[i] = Math.random() * 0.5 + 0.3 // 0.3 到 0.8 的随机大小
        phases[i] = Math.random() * Math.PI * 2 // 随机相位
      }

      particles.setAttribute('position', new THREE.BufferAttribute(positions, 3))
      particles.setAttribute('color', new THREE.BufferAttribute(colors, 3))
      particles.setAttribute('velocity', new THREE.BufferAttribute(velocities, 3))
      particles.setAttribute('size', new THREE.BufferAttribute(sizes, 1))
      particles.setAttribute('phase', new THREE.BufferAttribute(phases, 1))

      // 创建自定义着色器材质以实现脉冲效果
      const particleMaterial = new THREE.ShaderMaterial({
        uniforms: {
          time: { value: 0.0 },
          pointTexture: { value: this.createParticleTexture() }
        },
        vertexShader: `
          attribute float size;
          attribute float phase;
          attribute vec3 color;
          varying vec3 vColor;
          varying float vPhase;
          uniform float time;

          void main() {
            vColor = color;
            vPhase = phase;

            vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);

            // 脉冲大小效果
            float pulseSize = size * (1.0 + 0.5 * sin(time * 3.0 + phase));
            gl_PointSize = pulseSize * 50.0 * (300.0 / -mvPosition.z);

            gl_Position = projectionMatrix * mvPosition;
          }
        `,
        fragmentShader: `
          uniform sampler2D pointTexture;
          uniform float time;
          varying vec3 vColor;
          varying float vPhase;

          void main() {
            vec2 coords = gl_PointCoord;
            float distance = length(coords - 0.5);

            // 创建发光效果
            float alpha = 1.0 - smoothstep(0.0, 0.5, distance);

            // 脉冲透明度效果
            float pulse = 0.7 + 0.3 * sin(time * 4.0 + vPhase);
            alpha *= pulse;

            // 增强青色发光
            vec3 glowColor = vColor * (1.0 + 0.5 * pulse);

            gl_FragColor = vec4(glowColor, alpha);
          }
        `,
        transparent: true,
        blending: THREE.AdditiveBlending,
        depthWrite: false
      })

      const particleSystem = new THREE.Points(particles, particleMaterial)
      this.threeObjects.scene.add(particleSystem)
      this.threeObjects.flowParticles = particleSystem
      this.threeObjects.particleMaterial = particleMaterial // 保存材质引用用于动画
    },

    createParticleTexture() {
      // 创建粒子纹理
      const canvas = document.createElement('canvas')
      canvas.width = 64
      canvas.height = 64
      const context = canvas.getContext('2d')

      const gradient = context.createRadialGradient(32, 32, 0, 32, 32, 32)
      gradient.addColorStop(0, 'rgba(255, 255, 255, 1)')
      gradient.addColorStop(0.2, 'rgba(0, 255, 255, 0.8)')
      gradient.addColorStop(0.4, 'rgba(0, 255, 255, 0.4)')
      gradient.addColorStop(1, 'rgba(0, 255, 255, 0)')

      context.fillStyle = gradient
      context.fillRect(0, 0, 64, 64)

      const texture = new THREE.CanvasTexture(canvas)
      return texture
    },

    addLabel(text, x, y, z) {
      // 创建文字标签（使用简单的几何体代替，实际项目中可以使用CSS3DRenderer）
      const labelGeometry = new THREE.PlaneGeometry(2, 0.5)
      const labelMaterial = new THREE.MeshBasicMaterial({
        color: 0xffffff,
        transparent: true,
        opacity: 0.8
      })
      const label = new THREE.Mesh(labelGeometry, labelMaterial)
      label.position.set(x, y, z)
      // 避免直接访问camera.position，使用Vector3
      const cameraPos = new THREE.Vector3()
      cameraPos.copy(this.threeObjects.camera.position)
      label.lookAt(cameraPos)
      this.threeObjects.scene.add(label)
    },

    animate() {
      if (!this.threeObjects.renderer || !this.threeObjects.scene || !this.threeObjects.camera) return

      this.threeObjects.animationId = requestAnimationFrame(this.animate)

      try {
        // 更新时间用于着色器动画
        const time = Date.now() * 0.001
        if (this.threeObjects.particleMaterial && this.threeObjects.particleMaterial.uniforms) {
          this.threeObjects.particleMaterial.uniforms.time.value = time
        }

        // 旋转混合机搅拌器
        if (this.threeObjects.equipmentMeshes.mixer && this.threeObjects.equipmentMeshes.mixer.children[1]) {
          this.threeObjects.equipmentMeshes.mixer.children[1].rotation.y += 0.1
        }

        // 旋转回转窑
        if (this.threeObjects.equipmentMeshes.kiln) {
          this.threeObjects.equipmentMeshes.kiln.rotation.y += 0.02
        }

        // 更新粒子位置 - 沿着预定义路径流动
        if (this.threeObjects.flowParticles && this.threeObjects.flowPaths && this.threeObjects.flowParticles.geometry) {
          const positionAttribute = this.threeObjects.flowParticles.geometry.attributes.position
          const colorAttribute = this.threeObjects.flowParticles.geometry.attributes.color
          const velocityAttribute = this.threeObjects.flowParticles.geometry.attributes.velocity
          const sizeAttribute = this.threeObjects.flowParticles.geometry.attributes.size
          const phaseAttribute = this.threeObjects.flowParticles.geometry.attributes.phase

          if (positionAttribute && colorAttribute && velocityAttribute) {
            const positions = positionAttribute.array
            const velocities = velocityAttribute.array
            const colors = colorAttribute.array
            const sizes = sizeAttribute ? sizeAttribute.array : null
            const phases = phaseAttribute ? phaseAttribute.array : null

            for (let i = 0; i < positions.length; i += 3) {
              // 更新位置
              positions[i] += velocities[i]
              positions[i + 1] += velocities[i + 1]
              positions[i + 2] += velocities[i + 2]

              // 检查是否到达路径终点，重置到起点
              const particleIndex = Math.floor(i / 3)
              const pathIndex = particleIndex % this.threeObjects.flowPaths.length
              const path = this.threeObjects.flowPaths[pathIndex]

              const dx = positions[i] - path.end[0]
              const dy = positions[i + 1] - path.end[1]
              const dz = positions[i + 2] - path.end[2]
              const distance = Math.sqrt(dx * dx + dy * dy + dz * dz)

              if (distance < 0.5) {
                // 重置到起点
                positions[i] = path.start[0]
                positions[i + 1] = path.start[1]
                positions[i + 2] = path.start[2]

                // 添加一些随机性
                positions[i] += (Math.random() - 0.5) * 0.5
                positions[i + 1] += (Math.random() - 0.5) * 0.5
                positions[i + 2] += (Math.random() - 0.5) * 0.5

                // 重新设置相位
                if (phases) {
                  phases[particleIndex] = Math.random() * Math.PI * 2
                }
              }

              // 根据位置和时间调整颜色亮度（模拟能量脉冲）
              const intensity = 0.8 + 0.4 * Math.sin(time * 2.0 + (phases ? phases[particleIndex] : 0))
              colors[i] = path.color[0] * intensity
              colors[i + 1] = path.color[1] * intensity
              colors[i + 2] = path.color[2] * intensity

              // 动态调整粒子大小
              if (sizes) {
                const baseSizes = 0.3 + Math.random() * 0.5
                sizes[particleIndex] = baseSizes * (0.8 + 0.4 * Math.sin(time * 3.0 + (phases ? phases[particleIndex] : 0)))
              }
            }

            positionAttribute.needsUpdate = true
            colorAttribute.needsUpdate = true
            if (sizeAttribute) sizeAttribute.needsUpdate = true
            if (phaseAttribute) phaseAttribute.needsUpdate = true
          }
        }

        // 更新管道发光效果
        if (this.threeObjects.glowPipes) {
          this.threeObjects.glowPipes.forEach((glowPipe, index) => {
            if (glowPipe.material) {
              // 脉冲发光效果
              const pulseIntensity = 0.4 + 0.3 * Math.sin(time * 2.0 + index * Math.PI / 2)
              glowPipe.material.opacity = pulseIntensity

              // 根据管道类型调整发光颜色
              if (index === 1) { // 青色管道
                glowPipe.material.emissive.setRGB(0, pulseIntensity * 0.3, pulseIntensity * 0.3)
              }
            }
          })
        }

        // 更新轨道控制器
        if (this.threeObjects.controls) {
          this.threeObjects.controls.update()
        }

        // 渲染场景
        this.threeObjects.renderer.render(this.threeObjects.scene, this.threeObjects.camera)
      } catch (error) {
        console.error('Animation error:', error)
      }
    },

    startDataUpdate() {
      // 模拟数据更新
      setInterval(() => {
        this.processSteps.forEach((step, index) => {
          if (index < 4) {
            step.active = Math.random() > 0.2
          }
        })

        // 更新数值
        this.processSteps[0].value = Math.floor(Math.random() * 20 + 80) + '%'
        this.processSteps[2].value = Math.floor(Math.random() * 200 + 1100) + 'rpm'
        this.processSteps[3].value = Math.floor(Math.random() * 100 + 1400) + '°C'

        // 更新压力值，保留2位小数
        this.processSteps[0].pressure = (Math.random() * 1 + 2).toFixed(2) // 2.00-3.00 MPa
        this.processSteps[1].pressure = (Math.random() * 0.5 + 1.5).toFixed(2) // 1.50-2.00 MPa
        this.processSteps[2].pressure = (Math.random() * 1.5 + 3).toFixed(2) // 3.00-4.50 MPa
        this.processSteps[3].pressure = (Math.random() * 1 + 4).toFixed(2) // 4.00-5.00 MPa
        this.processSteps[4].pressure = (Math.random() * 0.5 + 1.7).toFixed(2) // 1.70-2.20 MPa
      }, 3000)
    },

    onMouseClick(event) {
      // 计算鼠标位置
      const rect = this.threeObjects.renderer.domElement.getBoundingClientRect()
      this.threeObjects.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1
      this.threeObjects.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1

      // 射线检测
      this.threeObjects.raycaster.setFromCamera(this.threeObjects.mouse, this.threeObjects.camera)
      const intersects = this.threeObjects.raycaster.intersectObjects(Object.values(this.threeObjects.equipmentMeshes), true)

      if (intersects.length > 0) {
        const clickedObject = intersects[0].object
        this.highlightEquipment(clickedObject)
      }
    },

    onMouseMove(event) {
      // 计算鼠标位置用于悬停效果
      const rect = this.threeObjects.renderer.domElement.getBoundingClientRect()
      this.threeObjects.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1
      this.threeObjects.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1

      // 射线检测
      this.threeObjects.raycaster.setFromCamera(this.threeObjects.mouse, this.threeObjects.camera)
      const intersects = this.threeObjects.raycaster.intersectObjects(Object.values(this.threeObjects.equipmentMeshes), true)

      // 更改鼠标样式
      this.threeObjects.renderer.domElement.style.cursor = intersects.length > 0 ? 'pointer' : 'default'
    },

    highlightEquipment(equipment) {
      // 重置所有设备的高亮状态
      Object.values(this.threeObjects.equipmentMeshes).forEach(mesh => {
        if (mesh.material) {
          mesh.material.emissive.setHex(0x000000)
        } else if (mesh.children) {
          mesh.children.forEach(child => {
            if (child.material) {
              child.material.emissive.setHex(0x000000)
            }
          })
        }
      })

      // 高亮选中的设备
      if (equipment.material) {
        equipment.material.emissive.setHex(0x444444)
      } else if (equipment.parent && equipment.parent.children) {
        equipment.parent.children.forEach(child => {
          if (child.material) {
            child.material.emissive.setHex(0x444444)
          }
        })
      }

      this.threeObjects.selectedEquipment = equipment
    },

    onWindowResize() {
      if (!this.threeObjects.camera || !this.threeObjects.renderer) return

      const width = this.$refs.threeContainer.clientWidth
      const height = this.$refs.threeContainer.clientHeight

      this.threeObjects.camera.aspect = width / height
      this.threeObjects.camera.updateProjectionMatrix()
      this.threeObjects.renderer.setSize(width, height)
    }
  }
}
</script>

<style scoped>
.process-flow-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #0c0c0c 0%, #1a1a1a 100%);
}

.three-container {
  width: 100%;
  height: 100%;
}

.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 10px;
  padding: 30px; /* 增加内边距 */
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  min-width: 250px; /* 增加最小宽度 */
}

.flow-status {
  display: flex;
  flex-direction: column;
  gap: 25px; /* 从15px增加到25px，增加了10px间距 */
}

.status-item {
  display: flex;
  align-items: center;
  gap: 15px; /* 从10px增加到15px */
  color: #fff;
  font-size: 16px; /* 从14px增加到16px */
  padding: 10px 0; /* 增加上下内边距 */
  border-bottom: 1px solid rgba(255, 255, 255, 0.1); /* 添加分隔线 */
}

.status-item:last-child {
  border-bottom: none; /* 最后一项不显示分隔线 */
}

.status-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 5px;
}

.status-name {
  font-weight: bold;
  color: #fff;
}

.status-details {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.status-icon {
  width: 16px; /* 从12px增加到16px */
  height: 16px; /* 从12px增加到16px */
  border-radius: 50%;
  background: #666;
  transition: all 0.3s ease;
  flex-shrink: 0; /* 防止图标缩小 */
}

.status-icon.active {
  background: #00ff88;
  box-shadow: 0 0 15px #00ff88; /* 增强发光效果 */
}

.status-value {
  color: #00ff88;
  font-weight: bold;
  font-size: 14px; /* 稍微小一点的字体 */
}

.status-pressure {
  color: #4da6ff;
  font-size: 12px;
  font-weight: normal;
}
</style>
